import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {InventoryService} from "../inventory.service";
import {EventBusService} from "../../services/event-bus.service";
import {ConfirmationService} from "primeng/primeng";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-borrow-restart',
  templateUrl: './borrow-restart.component.html',
  styleUrls: ['./borrow-restart.component.scss']
})
export class BorrowRestartComponent implements OnInit {
  display : boolean = false;
  zh;
  @Output() closeRestart = new EventEmitter;
  @Output() updateDev = new EventEmitter();
  @Input() currentBorrow;
  borrowRestartForm: FormGroup;
  minDate;
  InventoryData;
  windowSize;
  currentMaterial;
  width;
  nextStartDate;
  constructor( private inventoryService: InventoryService,
               private eventBusService:EventBusService,
               private confirmationService: ConfirmationService,
               private fb: FormBuilder) { }

  ngOnInit() {

    this.borrowRestartForm = this.fb.group({
      'remarsk': ['',Validators.required],
      'return_time':['', Validators.required],
    })

    this.windowSize = window.innerWidth;
    if(this.windowSize<1366){
      this.width = this.windowSize*0.4;
    }else{
      this.width = this.windowSize*0.4;
    }
    this.display = true;
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ "周一","周二","周三","周四","周五","周六","周日" ],
      dayNamesShort: [ "一","二","三","四","五","六","七" ],
      dayNamesMin: [ "一","二","三","四","五","六","七" ],
      monthNames: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月" ],
      monthNamesShort: [ "一","二","三","四","五","六","七","八","九","十","十一","十二" ],
    };

    this.InventoryData = {
      "sid":this.currentBorrow.sid,
      "type": "",
      "return_time": "",
      "urgency": "",
      "remarks": "",
      "inventories": []
    }
    this.dateAdd('');
    this.minDate = new Date(this.nextStartDate);

  }
  updateInventoryContent(){

    this.inventoryService.restartqueryDelivery(this.InventoryData).subscribe(data => {
      this.eventBusService.borrow.next(this.currentBorrow.status);
      this.updateDev.emit(false)
    },(err: Error) => {
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===0||JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，请联系管理员或稍后重试'
      }else{
        message = err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    });
  }
   dateAdd(startDate) {
    startDate = new Date(this.currentBorrow['return_time']);
    startDate = +startDate + 1000*60*60*24;
     startDate = new Date(startDate);
     this.nextStartDate = startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();
     return this.nextStartDate;
   }
   closeRestartMask(bool){
      this.closeRestart.emit(bool);
   }
}
